package com.shiguiwu.springboot3.service;

import com.shiguiwu.springboot3.dto.AuthUser;
import com.shiguiwu.springboot3.entity.MemberLoginLog;
import com.shiguiwu.springboot3.mapper.MemberLoginLogMapper;
import com.shiguiwu.springboot3.util.AddressUtils;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @description: 日志服务
 * @author: stone
 * @date: Created by 2025/10/26 13:40
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springboot3.service
 */
@Service
public class MemberLoginLogService {

    @Autowired
    private MemberLoginLogMapper memberLoginLogMapper;


    public boolean insertMemberLoginLog(MemberLoginLog memberLoginLog) {
        memberLoginLogMapper.insert(memberLoginLog);
        return false;
    }

    public void saveLog(boolean isError, String msg, String ip, UserAgent userAgent, AuthUser currentMember) {
        MemberLoginLog memberLoginLog = new MemberLoginLog();
        memberLoginLog.setOs(userAgent.getOperatingSystem().getName());
        memberLoginLog.setIpaddr(ip);
        memberLoginLog.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        memberLoginLog.setMsg(msg);
        memberLoginLog.setLoginTime(LocalDateTime.now());
        memberLoginLog.setStatus(isError ? "1" : "0");
        memberLoginLog.setBrowser(userAgent.getBrowser().getName());
        memberLoginLog.setMemberId(isError ? -1L:currentMember.getId());
        memberLoginLog.setUsername(currentMember.getUsername());
        memberLoginLog.setNickname(isError ? "" : currentMember.getUsername());

        memberLoginLogMapper.insert(memberLoginLog);
    }
}
